<template>
  <div class="app-container">
    <el-form
      label-position="top"
      v-show="state.showSearch"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
    >
      <el-form-item label="公司名称" prop="companyId">
        <ApiSelect
          class="form-input"
          v-model="queryParams.companyId"
          :api="selectState.company.api"
          :params="selectState.company.params"
          :valueField="selectState.company.valueField"
          :labelField="selectState.company.labelField"
          :immediate="true"
          clearable
        />
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        <ApiSelect
          class="form-input"
          v-model="queryParams.areaId"
          :api="selectState.area.api"
          :params="{ companyId: queryParams.companyId }"
          :valueField="selectState.area.valueField"
          :labelField="selectState.area.labelField"
          :immediate="immediate"
        />
      </el-form-item>
      <el-form-item label="线路名称" prop="routeId">
        <ApiSelect
          class="form-input"
          v-model="queryParams.routeId"
          :api="selectState.route.api"
          :params="{ areaId: queryParams.areaId }"
          :valueField="selectState.route.valueField"
          :labelField="selectState.route.labelField"
          :immediate="immediate"
        />
      </el-form-item>
      <el-form-item label="点位名称" prop="positionId">
        <ApiSelect
          class="form-input"
          v-model="queryParams.positionId"
          :api="selectState.point.api"
          :params="{ routeId: queryParams.routeId }"
          :valueField="selectState.point.valueField"
          :labelField="selectState.point.labelField"
          :immediate="immediate"
        />
      </el-form-item>
      <el-form-item label="点位类型" prop="positionTypeId">
        <ApiSelect
          class="form-input"
          v-model="queryParams.positionTypeId"
          :api="selectState.type.api"
          :checkParams="false"
          :valueField="selectState.type.valueField"
          :labelField="selectState.type.labelField"
        />
      </el-form-item>
      <el-form-item label="点位标签" prop="label">
        <el-select v-model="queryParams.label" placeholder="请选择">
          <el-option label="特殊点位" :value="1" />
          <el-option label="普通点位" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="machineType">
        <el-select
          v-model="queryParams.machineType"
          placeholder="请选择"
          filterable
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="machineSn">
        <el-input class="form-input" v-model="queryParams.machineSn" placeholder="设备编号" />
      </el-form-item>
      <el-form-item label="设备名称" prop="machineName">
        <el-input
          class="form-input"
          v-model="queryParams.machineName"
          maxlength="12"
          placeholder="设备名称"
        />
      </el-form-item>
      <el-form-item label="维修负责人" prop="serviceContracts">
        <el-input
          class="form-input"
          v-model="queryParams.serviceContracts"
          placeholder="维修负责人"
        />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select class="form-input" v-model="queryParams.enable" placeholder="请选择" clearable>
          <el-option
            v-for="dict in sys_common_staus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="网络状态" prop="onlineStatus">
        <el-select
          class="form-input"
          v-model="queryParams.onlineStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in [
              { label: '在线', value: 1 },
              { label: '离线', value: 0 }
            ]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" justify="space-between">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['machine:machine:add']" @click="handleAdd">
          新增
        </el-button>
      </el-col>

      <el-col :span="20">
        <el-row :gutter="10" justify="end" style="align-items: center">
          <div class="icon-group">
            <div>
              <el-icon>
                <svg-icon icon-class="tree" />
              </el-icon>
              总数：{{ deviceCountObj?.machineSize ?? 0 }}
            </div>
            <div class="success">
              <el-icon>
                <svg-icon icon-class="list" />
              </el-icon>
              在线：{{ deviceCountObj?.online ?? 0 }}
            </div>
            <div class="offline">
              <el-icon>
                <svg-icon icon-class="list" />
              </el-icon>
              离线：{{ deviceCountObj?.offline ?? 0 }}
            </div>
          </div>

          <right-toolbar
            v-model:showSearch="state.showSearch"
            @queryTable="getList"
            style="margin-left: 10px"
          ></right-toolbar>
        </el-row>
      </el-col>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList">
      <el-table-column
        fixed="left"
        label="序号"
        align="center"
        type="index"
        :index="indexAdd"
        width="50"
      />
      <el-table-column
        label="设备编号"
        align="center"
        prop="machineSn"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          <el-link :underline="false" :type="tableRowClassName({ row })">{{
            row.machineSn
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center" prop="companyName" width="150" />
      <el-table-column label="区域名称" align="center" prop="areaName" width="150" />
      <el-table-column label="线路名称" align="center" prop="routeName" width="150" />
      <el-table-column
        label="点位名称"
        width="120"
        align="center"
        prop="positionName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="点位类型"
        align="center"
        prop="positionTypeName"
        :show-overflow-tooltip="true"
      />

      <el-table-column label="点位标签" align="center" prop="label">
        <template #default="{ row }">
          <span>{{ row.label === 1 ? '特殊点位' : '普通点位' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="设备名称" align="center" prop="machineName" width="120" />
      <el-table-column label="设备类型" align="center" prop="machineType">
        <template #default="{ row }">
          <dict-tag :options="device_type" :value="row.machineType" />
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" prop="machineModel" />
      <el-table-column label="维修负责人" align="center" prop="serviceName" width="100" />
      <el-table-column label="冷藏温度(°C)" align="center" prop="temperature">
        <template #default="{ row }">
          <el-link
            :underline="false"
            :type="row.temperature > 10 || row.temperature < 0 ? 'danger' : 'primary'"
            @click="handleTemperature(row)"
            >{{ row.temperature }}</el-link
          >
        </template>
      </el-table-column>
      <el-table-column label="开门检测" align="center" prop="openDoorCheck">
        <template #default="{ row }">
          <dict-tag :options="device_status" :value="row.openDoorCheck" />
        </template>
      </el-table-column>
      <el-table-column label="关门检测" align="center" prop="closeDoorCheck">
        <template #default="{ row }">
          <dict-tag :options="device_status" :value="row.closeDoorCheck" />
        </template>
      </el-table-column>
      <el-table-column label="出餐检测" align="center" prop="outMealCheck">
        <template #default="{ row }">
          <dict-tag :options="device_status" :value="row.outMealCheck" />
        </template>
      </el-table-column>
      <el-table-column label="取餐检测" align="center" prop="takeMealCheck">
        <template #default="{ row }">
          <dict-tag :options="device_status" :value="row.takeMealCheck" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="设备用电量(kwh)" align="center" prop="kwh" /> -->
      <el-table-column label="运营状态" width="100" align="center" prop="operationStatus">
        <template #default="{ row }">
          <dict-tag :options="device_sale_status" :value="row?.operationStatus" />
        </template>
      </el-table-column>
      <el-table-column label="设备销售额(元)" width="100" align="center" prop="salesAmount" />
      <el-table-column label="设备库存" width="100" align="center" prop="comboTotal">
        <template #default="{ row }">
          <el-link :underline="false" :type="handleInventoryTextColor(row)">{{
            row.comboTotal
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="enable">
        <template #default="{ row }">
          <dict-tag :options="sys_common_staus" :value="row.enable" />
        </template>
      </el-table-column>
      <el-table-column label="网络状态" align="center" prop="onlineStatus">
        <template #default="{ row }">
          <div :class="[row.onlineStatus ? 'net-ball-on' : 'net-ball-off']"></div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="客服状态" align="center" prop="operationalOnlineStatus">
        <template #default="{ row }">
          <img
            style="width: 20px"
            @click="openOnLineList(row.machineId)"
            :src="
              row.operationalOnlineStatus
                ? 'https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/17/在线_20250117151345A168.png'
                : 'https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/17/离线 1_20250117151445A169.png'
            "
            alt=""
          />
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            v-hasPermi="['machine:machine:query']"
            @click="handleTableAction(row, 'detail')"
            >管理</el-button
          >
          <ConfirmButton
            v-hasPermi="['machine:machine:dis']"
            :row="row"
            tipText="此设备"
            @confirm="handleTableAction"
          />
          <el-button
            :disabled="!row.serialNumber"
            link
            type="primary"
            v-hasPermi="['machine:machine:views']"
            @click="handleViews(row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <AddDevice ref="addDeviceRef" @refresh="handleSearch" />
    <temperature ref="temperatureRef" />
    <CameraPopup ref="cameraPopup" />
    <OnlineList ref="onlineRef" />
  </div>
</template>

<script setup name="DeviceManage">
import { ElMessage } from 'element-plus'
import { getDeviceList, disableDevice, getDeviceCount } from '@/api/device'
import { useOrganApiConfig } from '@/hooks/service'
import AddDevice from './components/AddDevice'
import temperature from './components/temperature'
import CameraPopup from './components/CameraPopup'
import { useDict } from '@/utils/dict'
import { nextTick } from 'vue'
import OnlineList from './components/onlineList.vue'

const router = useRouter()
const route = useRoute()
const selectState = useOrganApiConfig()
const queryRef = ref(null)
const addDeviceRef = ref()
const temperatureRef = ref()
const cameraPopup = ref()
const onlineRef = ref()
const deviceCountObj = ref({})
const { sys_common_staus, device_type, device_status, device_sale_status } = useDict(
  'sys_common_staus',
  'device_type',
  'device_status',
  'device_sale_status'
)
const immediate = ref(false)
const state = reactive({
  showSearch: true,
  total: 0,
  loading: false
})
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})

const tableList = ref([])

const tableRowClassName = ({ row }) => {
  return !(+row.temperature > 10 || +row.temperature < 0) &&
    +row.comboTotal > +row.threshold &&
    !row?.warning
    ? 'default'
    : 'danger'
}
function handleInventoryTextColor(row) {
  return +row.comboTotal < +row.threshold ? 'danger' : 'primary'
}
function handleSearch(confirm) {
  if (!confirm) queryRef.value.resetFields()

  queryParams.pageNum = 1
  getList()
}

// type序号 - 页面切换递增
function indexAdd(index) {
  const { pageNum, pageSize } = queryParams
  return index + 1 + (pageNum - 1) * pageSize
}

async function getList() {
  state.loading = true

  getDeviceCount(queryParams).then((r) => {
    deviceCountObj.value = r.data ?? {}
  })

  getDeviceList(queryParams)
    .then((r) => {
      // 多参数判断警告
      r?.rows?.map((item) => {
        const { openDoorCheck, closeDoorCheck, outMealCheck, takeMealCheck, onlineStatus } = item

        item.warning =
          !openDoorCheck || !closeDoorCheck || !outMealCheck || !takeMealCheck || !onlineStatus
      })

      tableList.value = r.rows
      state.total = r.total
    })
    .finally(() => {
      state.loading = false
    })
}

/**table Action */
function handleAdd() {
  addDeviceRef.value?.init()
}

// 温度
function handleTemperature(row) {
  temperatureRef.value?.init(row)
}
function handleTableAction({ machineId }, operType) {
  if (operType == 'detail') {
    router.push({ path: '/device/deviceDetail', query: { id: machineId } })
  } else {
    disableDevice(machineId).then(() => {
      ElMessage.success('操作成功')
      getList()
    })
  }
}
/**跳转到萤石地址查看设备 */
function handleViews(row) {
  cameraPopup.value.init(row?.serialNumber)
}
// 保存路由参数
const routeParmas = ref({})
// 根据路由参数，设置查询参数
function setQueryModel() {
  const { companyId, areaId, routeId, positionId } = route.query

  if (positionId) {
    queryParams.companyId = companyId
    queryParams.areaId = areaId
    queryParams.routeId = routeId
    queryParams.positionId = positionId

    routeParmas.value = route.query
    immediate.value = true
  }
}

// 页面是否已加载
const mounted = ref(false)
onActivated(() => {
  // 初始化页面时不执行
  if (!mounted.value) return

  // 页面路由参数变化
  if (route.query.positionId && JSON.stringify(routeParmas.value) !== JSON.stringify(route.query)) {
    queryRef.value.resetFields()
    const keys = ['companyId', 'areaId', 'routeId', 'positionId']
    // 延迟按顺序加载数据，解决联动ApiSelect组件自动触发清楚问题
    keys.map((k, i) => {
      setTimeout(() => {
        queryParams[k] = route.query[k]
      }, 100 * i)
    })

    // 数据加载完成后请求
    setTimeout(getList, 500)
    routeParmas.value = route.query
    immediate.value = true
  } else {
    getList()
  }
})

// 查看客服在线列表
function openOnLineList(machineId) {
  onlineRef.value?.init(machineId)
}

onMounted(() => {
  setQueryModel()
  getList()
  nextTick(() => {
    mounted.value = true
  })
})
</script>

<style lang="scss" scoped>
:deep(.warning-row) {
  background-color: var(--el-color-error-light-5);
}
.success {
  color: var(--el-color-success);
}
.offline {
  color: var(--el-color-info);
}
.icon-group {
  display: flex;
  justify-content: flex-end;
  > div {
    margin-right: 15px;
    display: flex;
    align-items: center;
    font-size: 14px;
    .el-icon {
      margin-right: 8px;
      font-size: 22px;
    }
  }
}

.form-input {
  width: 210px;
}
</style>
